package org.budo.sms.service.movek;

import java.util.Map;

import org.budo.sms.service.api.BudoSmsService;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.lang.util.NumberUtil;
import org.budo.support.lang.util.StringUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class BudoMovekSmsService implements BudoSmsService {
    private static final String URL = "http://api.movek.net:8513/sms/Api/Send.do";

    private String spCode;

    private String loginName;

    private String password;

    @Override
    public String sendSms(String to, String template, Map<String, Object> parameters) {
        if (null == template || template.trim().isEmpty()) {
            log.error("#33 sendSms error, to=" + to + ", template=" + template + ", parameters=" + parameters);
            throw new IllegalArgumentException("#34 发送短信失败, template 为空, template = " + template);
        }

        Request request = new Request();
        request.setMethod(Request.POST);
        request.setUrl(URL);

        request.setField("SpCode", this.getSpCode());
        request.setField("LoginName", this.getLoginName());
        request.setField("Password", this.getPassword());

        String messageContent = this.mergeMessageContent(template, parameters);

        request.setField("MessageContent", messageContent);
        request.setField("UserNumber", to);
        request.setField("SerialNumber", "SerialNumber");

        Response response = request.execute();
        String responseBody = response.getBody();
        Integer status = response.getStatus();

        if (!NumberUtil.equals(200, status)) {
            log.error("#43 Movek sendSms error, response=" + response);
            return responseBody;
        }

        if (StringUtil.contains(responseBody, "result=0") // 成功
                && !StringUtil.contains(responseBody, "需要人工审核")) { // 不需审核
            return responseBody; // 成功
        }

        log.error("#53 response=" + response + ", request=" + request);
        return responseBody;
    }

    /**
     * 这里没做模板,tj-message做了
     */
    private String mergeMessageContent(String template, Map<String, Object> parameters) {
        return template;
    }
}